package com.tanhua.manage.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manage.domain.AnalysisByDay;
import com.tanhua.manage.mapper.AnalysisByDayMapper;
import com.tanhua.manage.mapper.LogMapper;
import com.tanhua.manage.utils.ComputeUtil;
import com.tanhua.manage.vo.AnalysisSummaryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisByDayService extends ServiceImpl<AnalysisByDayMapper, AnalysisByDay> {


    @Autowired
    private AnalysisByDayMapper byDayMapper;

    @Autowired
    private LogMapper logMapper;

    /**
     * 统计首页数据摘要
     */
    public ResponseEntity summary() {

        Date date = new Date();
        //获取当前时间字符串
        String now = new SimpleDateFormat("yyyy-MM-dd").format(date);
        //获取昨天
        String yestoday=ComputeUtil.offsetDay(date,-1);

        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        //SELECT SUM(num_registered) FROM tb_analysis_by_day
        //AnalysisByDay analysis = query().select(" SUM(num_registered) as numActive").one();
        vo.setCumulativeUsers(byDayMapper.queryCumulativeUsers());
        //2、过去30天和7天的活跃用户数
        Long num7 = byDayMapper.queryNumActiveByDate(ComputeUtil.offsetDay(date, -7), now);//过去7天
        Long num30 = byDayMapper.queryNumActiveByDate(ComputeUtil.offsetDay(date,-30),now);//过去30天
        vo.setActivePassWeek(num7);
        vo.setActivePassMonth(num30);

        //3、新增的用户
        AnalysisByDay recordDate = query().eq("record_date", now).one();
        AnalysisByDay yesDate = query().eq("record_date", yestoday).one();
        vo.setNewUsersToday(recordDate.getNumRegistered()==null?0:recordDate.getNumRegistered().longValue());
        vo.setNewUsersTodayRate(ComputeUtil.computeRate(recordDate.getNumRegistered(),yesDate.getNumRegistered()));
        //4、今日登录的数量
        vo.setLoginTimesToday(recordDate.getNumLogin().longValue());
        vo.setLoginTimesTodayRate(ComputeUtil.computeRate(recordDate.getNumLogin(),yesDate.getNumLogin()));
        //5、今日活跃的数量
        vo.setActiveUsersToday(recordDate.getNumActive().longValue());
        vo.setActiveUsersTodayRate(ComputeUtil.computeRate(recordDate.getNumActive(),yesDate.getNumActive()));

        return ResponseEntity.ok(vo);
    }

    /**
     * 数据统计
     *  按照日期 统计tb_log日志表中的数据
     *  写入到tb_analysis_by_day
     */
    public void analysis() {
        //1、获取统计的日期
        String todayStr = DateUtil.formatDate(new Date());  //2020-11-14
        String yestodayStr = ComputeUtil.offsetDay(new Date(), -1); //2020-11-13
        Date today = DateUtil.parse(todayStr);  //今日date对象
        //2、根据日期，查询tb_analysis_by_day是否有今日的统计记录
        //如果是第一次统计，创建一条今日的统计数据
        QueryWrapper<AnalysisByDay> queryWrapper = new QueryWrapper();
        queryWrapper.eq("record_date", today);
        AnalysisByDay analysis = byDayMapper.selectOne(queryWrapper);
        if(analysis == null) {
            //不存在，今日第一次统计。保存一天数据到数据库
            analysis = new AnalysisByDay();
            analysis.setRecordDate(today);
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            byDayMapper.insert(analysis);
        }
        //3、统计log表中，今日的注册人数
        Integer registerNum = logMapper.queryNumsByType(todayStr,"0102");
        analysis.setNumRegistered(registerNum);
        //4、统计log表中，今日的登录人数
        Integer loginNum = logMapper.queryNumsByType(todayStr,"0101");
        analysis.setNumLogin(loginNum);
        //5、统计log表中，今日的活跃人数
        Integer activeNum = logMapper.queryNumsByDate(todayStr);
        analysis.setNumActive(activeNum);
        //6、统计log表中，次日留存用户
        Integer numRetention1d = logMapper.queryRetention1d(todayStr,yestodayStr);
        analysis.setNumRetention1d(numRetention1d);
        //更新tb_analysis_by_day表
        byDayMapper.updateById(analysis);
    }
}
